package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.remote.service.ApiHomeService;
import com.web.exiaodao.remote.service.ApiMakeMoneyTableService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.SearchVo;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.excelUtil.ExcelColumn;
import com.web.webstart.base.excelUtil.ExcelHead;
import com.web.webstart.base.excelUtil.ExcelHelper;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.encryptDir.MD5Util;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import static com.web.webstart.base.util.XaUtil.dealMobileStr;

/**
 * Created by duandazhi on 2016/12/12.
 */
@Service("ApiHomeService")
@Transactional(readOnly = false)
public class ApiHomeServiceImpl extends BaseService implements ApiHomeService {

    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiMakeMoneyTableService makeMoneyTableService;
    @Autowired
    private UserRepository userRepository;

    private static final Logger LOGGER = Logger.getLogger(ApiFranchiseTableServiceImpl.class);

    /**
     *
     * {@link JConstant.Search_Share_FavType}
     * 搜索模块:搜索模块(服务;机构;住;商城;玩;游学)
     *
     * 方法1:先联合在筛选 数据过多,可能影响性能
     * 方法2:先筛选在联合
     *
     * 1:用union,看要不要分页,如果分页比较麻烦;
     * 2:随机打乱 不同的数据库打乱是不一样的，sql server里面用的是 guid
     * 3:记得用union all 不要用union
     *
     *
     *<code>
     select * from (
     select name '类型1' from a表
     union
     select name '类型2' from b表
     ) result limit 0,100
     <code/>
     *
     *<code>
     select * from (
     select name '类型1' from a表 where name like '%aaa%'
     union
     select name '类型2' from b表 where name like '%aaa%'
     ) result limit 0,100
     <code/>
     */
    @Override
    public XaResult<List<SearchVo>> searchByKey(String searchKey)  throws BusinessException  {
        XaResult<List<SearchVo>> xr = new XaResult<>();
        List<Object> params = new ArrayList();
        params.add("%"+ searchKey.trim() +"%");
        params.add(0);
        params.add(2000);
        String proSql = "CALL pro_home_search(?,?,?)";
        List<Object[]> objs = this.queryCall(proSql,params);
        List<SearchVo> searchVos = new ArrayList<>();
        for (Object[] mVo : objs) {
            SearchVo vo = new SearchVo();
            vo.setObjectId(((BigInteger)mVo[0]).longValue());//??
            vo.setName(mVo[1] == null ? "" : (String)mVo[1]);
            vo.setType(((BigInteger)mVo[2]).longValue());//??
            vo.setTypeName(mVo[3] == null ? "" : (String)mVo[3]);
            searchVos.add(vo);
        }
        xr.setObject(searchVos);
        return xr;
    }

    @Override
    public XaResult<List<UserVo>> importCustomersUserData(InputStream excelIputStream) throws BusinessException {
        XaResult<List<UserVo>> xr = new XaResult<>();
        //excel结构
        List<ExcelColumn> excelColumns = new ArrayList<>();
        excelColumns.add(new ExcelColumn(0, "id", "用户编号", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(1, "mobile", "手机号码", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(2, "userName", "用户名", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(3, "recommendPhone", "推荐人", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(4, "createTime", "注册时间", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(5, "balanceCoin", "孝亲币", Cell.CELL_TYPE_STRING));

        //设置头部
        ExcelHead head = new ExcelHead();
        head.setRowCount(2); // 模板中头部所占行数
        head.setColumns(excelColumns);  // 列的定义
        //执行导出,第一个null是response参数，用来输出到浏览器，第二个null是要导出的数据集合
        List<UserVo> voList = (List<UserVo>) ExcelHelper.getInstanse().importToObjectList(head, excelIputStream, UserVo.class);
        xr.setObject(voList);

        if (true) {//todo
           // return null;
        }

        if (true && voList != null) {//初始化一次数据；向数据库插入数据
            //默认密码全部是123456
            LOGGER.info("开始导入数据：" + voList.size());
            for (int i = 0; i < voList.size(); ++i) {
                UserVo userVo = voList.get(i);
                User user = JSON.parseObject(JSON.toJSONString(userVo), User.class);
                if (XaUtil.isEmpty(user)) {
                    continue;
                }
                if (XaUtil.isEmpty(user.getMobile())) {
                    continue;
                }
                user.setPassword(MD5Util.getMD5String("123456"));
                user.setRecommendPhone(dealMobileStr(user.getRecommendPhone()));
                user.setMobile(dealMobileStr(user.getMobile()));
                user.setId(null);
                //插入用户
                String mobile = user.getMobile();
                User userTemp = userService.validMobile(mobile);


                if (userTemp != null) {
                    user.setPassword(userTemp.getPassword());
                    user.setRecommendPhone(userTemp.getRecommendPhone());
                }
                //保存用户
                user = userRepository.save(user);
                //插入亲币数据
                    makeMoneyTableService.saveMakeMoneyRecord(user.getId(),
                        JConstant.ConsumeOrMakeMoney.MakeMoney,
                        userVo.getBalanceCoin() != null ? userVo.getBalanceCoin().intValue() : 0,
                        JConstant.IntegralTypeEnum.OLD_SYSTEM.getIndex());

            }
            LOGGER.info("开始导入数据完成");
        } else  {
            LOGGER.info("数据已经导入，请不要重复导入");
        }
        return xr;
    }

}
